/**
 * 阿里云短信服务
 * 用于发送价格预警和黑名单通知等政采云业务短信
 */
const Core = require('@alicloud/pop-core');
const { SM4 } = require('../lib/zcy-crypto');

class SmsService {
  constructor(app) {
    this.app = app;
    this.config = app.config.aliyunSms;
    this.client = new Core({
      accessKeyId: this.config.accessKeyId,
      accessKeySecret: this.config.secret,
      endpoint: 'https://dysmsapi.aliyuncs.com',
      apiVersion: '2017-05-25'
    });
  }

  /**
   * 发送价格预警短信
   * @param {Array<string>} phoneNumbers - 接收手机号列表
   * @param {Object} params - 短信参数
   * @returns {Promise<Object>} 发送结果
   */
  async sendPriceAlert(phoneNumbers, params) {
    return this._sendSms(
      phoneNumbers,
      this.config.templates.priceAlert,
      params,
      'PRICE_ALERT'
    );
  }

  /**
   * 发送黑名单通知短信
   * @param {Array<string>} phoneNumbers - 接收手机号列表
   * @param {Object} params - 短信参数
   * @returns {Promise<Object>} 发送结果
   */
  async sendBlacklistNotice(phoneNumbers, params) {
    return this._sendSms(
      phoneNumbers,
      this.config.templates.blacklistNotice,
      params,
      'BLACKLIST_NOTICE'
    );
  }

  /**
   * 通用发送短信方法
   * @private
   */
  async _sendSms(phoneNumbers, templateCode, params, businessType) {
    if (!phoneNumbers || phoneNumbers.length === 0) {
      this.app.logger.warn(`[SmsService] 未提供接收手机号，业务类型: ${businessType}`);
      return { success: false, message: '未提供接收手机号' };
    }

    try {
      // 加密手机号日志记录
      const encryptedPhones = phoneNumbers.map(phone => SM4.encrypt(phone, this.app.config.crypto.sm4Key));
      this.app.logger.info(`[SmsService] 准备发送短信，业务类型: ${businessType}，加密手机号: ${encryptedPhones.join(',')}`);

      const requestOption = { method: 'POST' };
      const phoneStr = phoneNumbers.join(',');
      const paramsStr = JSON.stringify(params);

      const result = await this.client.request('SendSms', {
        PhoneNumbers: phoneStr,
        SignName: this.config.signName,
        TemplateCode: templateCode,
        TemplateParam: paramsStr
      }, requestOption);

      // 记录短信发送审计日志
      await this.app.model.SmsAudit.create({
        business_type: businessType,
        phone_numbers: encryptedPhones.join(','),
        template_code: templateCode,
        params: paramsStr,
        send_result: JSON.stringify(result),
        success: result.Code === 'OK',
        operator_id: this.app.currentUser?.id || 0
      });

      if (result.Code !== 'OK') {
        this.app.logger.error(`[SmsService] 短信发送失败，业务类型: ${businessType}，错误码: ${result.Code}，错误信息: ${result.Message}`);
        return { success: false, code: result.Code, message: result.Message };
      }

      return { success: true, requestId: result.RequestId, bizId: result.BizId };
    } catch (error) {
      this.app.logger.error(`[SmsService] 短信发送异常，业务类型: ${businessType}，错误:`, error);
      return { success: false, message: error.message };
    }
  }
}

module.exports = SmsService;